package com.starpl.mobile.android.monthunsae.november.handler;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.starpl.mobile.android.monthunsae.november.R;
import com.starpl.mobile.android.monthunsae.november.activity.MessageBlockActivity;
import com.starpl.mobile.android.monthunsae.november.activity.MessageHistoryActivity;
import com.starpl.mobile.android.platform.command.StarplCommand;
import com.starpl.mobile.android.platform.common.image.ImageDownloader;
import com.starpl.mobile.android.platform.common.network.HttpHandler;
import com.starpl.mobile.android.platform.component.BaseListHandler;
import com.starpl.mobile.android.platform.domain.StarplMessage;

/**
 * 쪽지 목록 리스트 핸들러
 * 가장 최근 쪽지를 보낸 순으로 유저 목록을 받아옵니다.
 * 목록에서 선택하면 쪽지 히스토리를 볼 수 있습니다.
 * 
 * @author 우연화
 * @since 2011.05.03 / 기존의 Custom Adapter에서 플랫폼의 리스트 핸들러로 변경합니다.
 */
public class MessageListHandler extends BaseListHandler implements OnClickListener
{
	
	private ArrayList<StarplMessage> mMessageList;
	private String mUserId;
	private String mNickName;
	private int mPage;

	/**
	 * 쪽지 목록 핸들러 생성자
	 * 
	 * @param activity
	 * @param userId
	 */
	public MessageListHandler(Activity activity, String userId, String nickName)
	{
		super(activity);
		this.mMessageList = new ArrayList<StarplMessage>();
		this.mUserId = userId;
		this.mNickName = nickName;
		this.mPage = 1;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#getArrayList()
	 */
	@Override
	public ArrayList<?> getArrayList()
	{
		return mMessageList;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#getRowView(int, android.view.View)
	 */
	@Override
	public View getRowView(int position, View convertView)
	{
		StarplMessage message = mMessageList.get(position);
		
		convertView = inflate(R.layout.message_row);

		LinearLayout llMessageBackImage = (LinearLayout)convertView.findViewById(R.id.message_row_ll_message);
		ImageView ivProfile = (ImageView)convertView.findViewById(R.id.message_row_iv_profile);
		TextView tvNickname = (TextView)convertView.findViewById(R.id.message_row_tv_nickname);
		TextView tvComment = (TextView)convertView.findViewById(R.id.message_row_tv_comment);
		
		convertView.setTag(position);			
		
		if(message!=null)
		{
			// 새로운 메시지가 아닌 경우 배경이미지를 기본 이미지로 한다.
			if(message.getNewCount()==0)
			{
				llMessageBackImage.setBackgroundResource(R.drawable.bg_message);
			}
			// 새로운 메시지가 있을 경우 배경이미지를 변경한다.
			else
			{
				llMessageBackImage.setBackgroundResource(R.drawable.bg_message_new);
			}
			
			// 유저의 프로필 이미지를 세팅한다.
			ImageDownloader.download(message.getSendUserProfileImgPath(), ivProfile, true);
			
			tvNickname.setText(message.getSendStarName());
			tvComment.setText(message.getMsgContent());
		}
		
		return convertView;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#onRowClick(android.view.View)
	 */
	@Override
	public void onRowClick(View v)
	{
		StarplMessage message = mMessageList.get((Integer)v.getTag());
		
		Bundle extras = new Bundle();
		
		// sender 데이터 세팅
		int sendUserIdx = message.getSendUserIdx();
		String sendUserName = message.getSendStarName();
		String sendUserId = message.getUserId();
		
		extras.putInt("sendUserIdx", sendUserIdx);
		extras.putString("sendUserName", sendUserName);
		extras.putString("sendUserId", sendUserId);
		
		// 유저(receiver) 데이터 세팅
		extras.putString("userId", mUserId);
		extras.putString("nickname", mNickName);
		
		getNewActivity()
			.setTargetActivity(MessageHistoryActivity.class)
			.setBundle(extras)
			.show();
	}
	

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#onRowClear()
	 */
	@Override
	public void onRowClear()
	{
		mMessageList.clear();
		mPage = 1;
	}

	
	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#getHeaderView()
	 */
	@Override
	public View getHeaderView()
	{
		View convertView = mInflater.inflate(R.layout.message_header, null);
		
//		TextView tvInfo = (TextView)convertView.findViewById(R.id.message_header_tv_info);
		ImageButton ibMessageBlock = (ImageButton)convertView.findViewById(R.id.message_header_ib_message_block);
		
		ibMessageBlock.setOnClickListener(this);
		
		return convertView;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#loadContent()
	 */
	@Override
	public void loadContent()
	{
		HttpHandler getMessage = new HttpHandler(mParentActivity, "쪽지 목록을 읽어오는 중")
		{
			/* (non-Javadoc)
			 * @see com.starpl.platform.common.network.HttpHandler#didSucceed(java.lang.Object)
			 */
			@Override
			public void didSucceed(Object result)
			{
				try
				{
					JSONObject messageObject = (JSONObject)result;
					JSONArray dataList = messageObject.getJSONArray("data");
					JSONObject extData1 = messageObject.getJSONObject("extData1");
					mPage = extData1.getInt("nextPageNum");
					
					int dataSize = dataList.length();
					
					if(dataSize==0)
					{
						alert("받은 쪽지가 없습니다");
					}
					
					for(int i = 0 ; i < dataSize ; i++)
					{
						JSONObject data = (JSONObject) dataList.get(i);
						StarplMessage message = new StarplMessage(data);
						
						mMessageList.add(message);
					}
					
					// 다음페이지 정보를 받아와 토글 또는 푸터뷰에 대한 처리를 결정한다.
					if(mPage > 1)
					{
						toggleLockListView();
					}
					else
					{
						removeFooterView();
					}
					
					notifyDataSetChanged();
				}
				catch(JSONException e)
				{
					e.printStackTrace();
				}
			}
		};
		
		// 쪽지 목록을 받아온다
		StarplCommand.getMessage(getMessage, mUserId, mPage);
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#onInit()
	 */
	@Override
	public void onInit()
	{
		mListView.setDividerHeight(0);
		
		showHeaderView();
		showFooterView();
		setAdapter();
		loadContent();
	}

	@Override
	public void onClick(View v)
	{
		switch(v.getId())
		{
		case R.id.message_header_ib_message_block:
			getNewActivity().setTargetActivity(MessageBlockActivity.class).show();
			break;
		}
	}

}
